package org.example.juc.forkjoin;

import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveTask;
import java.util.function.DoublePredicate;

public class ForkJoinExample {

    public static void main(String[] args) {
        final int SIZE = 10000;
        double[] numbers = new double[SIZE];
        for (int i = 0; i < SIZE; i++) {
            numbers[i] = Math.random();
        }
        Counter counter = new Counter(numbers, 0, numbers.length, x -> x > 0.5);
        ForkJoinPool forkJoinPool = new ForkJoinPool();
        forkJoinPool.invoke(counter);
        System.out.println(counter.join());
    }
}

class Counter extends RecursiveTask<Integer> {
    public static final int THRESHOLD = 100;
    private double[] numbers;
    private int start;
    private int end;
    private DoublePredicate filter;

    public Counter(double[] numbers, int start, int end, DoublePredicate filter) {
        this.numbers = numbers;
        this.start = start;
        this.end = end;
        this.filter = filter;
    }

    @Override
    protected Integer compute() {
        if (end - start <= THRESHOLD) {
            int count = 0;
            for (int i = start; i < end; i++) {
                if (filter.test(numbers[i])) {
                    count++;
                }
            }
            return count;
        } else {
            int mid = (start + end) / 2;
            Counter left = new Counter(numbers, start, mid, filter);
            Counter right = new Counter(numbers, mid, end, filter);
            invokeAll(left, right);
            return left.join() + right.join();
        }
    }
}
